package com.pescamillam.kiosco.windows;


import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamResolution;
import com.pescamillam.kiosco.ImageSaved;
import com.pescamillam.kiosco.camera.Camera;
import com.pescamillam.kiosco.printer.Printer;
import com.pescamillam.kiosco.sql.Code;
import com.pescamillam.kiosco.sql.SqlConnection;
import com.pescamillam.kiosco.util.Constants;

//TODO agregar lectura de nombre por base de datos
public class TakePictureFrame extends JFrame{
	/** auto uid */
	private static final long serialVersionUID = -2769192314026452292L;
	JPanel cameraPanel;
	Webcam webcam;
	JLabel nameLabel, documentLabel, dataLabel, serialLabel;
	JTextField serialNumber; 
	JButton takePictureButton, resetButton ,acceptButton, backButton, keyboardButton ;
	JComboBox<String> deviceList, trademarkList;
	JLabel imageLabel;
	private String[] deviceString = { "Seleccione","Portatil","Tablet","Camara","Otro"};	
	private String[] laptopString = { "Seleccione","Acer","Alienware","Asus","CybertronPC","Dell","Gateway","Gigabyte","HP","Lenovo","MSI","Rain Computers","Samsung","Toshiba","Wyse","Otro"};
	private String[] tabletString = { "Seleccione","Acer ","Amazon ","Asus ","Craig Electronics ","Dell ","Genius ","HP ","IVIEW ","Lenovo ","LG ","LUFTCO ","MSI Computer Corp. ","NVIDIA ","Polaroid ","Samsung ","Supersonic ","Toshiba ","Otro"};
	private String[] camString = { "Seleccione","BlueLotus","Casio","Coleman","Fujifilm","General Electric","iRulu","Kodak","Nikon","Polaroid ","Samsung","Sony","SVP","Vivitar","Zmodo","Otro"};
	
	String id = "";
	
	boolean emulatePrinter = false;
	
	private static TakePictureFrame instance;
	
	private TakePictureFrame() {
		
	}
	
	public static TakePictureFrame getInstance() {
		if (instance == null) {
			instance = new TakePictureFrame();
			instance.init();
			instance.setExtendedState(JFrame.MAXIMIZED_BOTH);
			instance.setUndecorated(true);
			instance.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		}
		return instance;
	}
	
	public void identify(String id) {
		this.id = id;
		documentLabel.setText("Id: "+id);
		nameLabel.setText("Bienvenido " + getPersonName(id));
		if (cameraPanel != null) {
			if (!((WebcamPanel)cameraPanel).isStarted()) { 
				startCamera();
			}
			cameraPanel.setVisible(true);
		}
		if (imageLabel.isVisible()) {
			imageLabel.setVisible(false);
		}
		ImageSaved.getInstance().setImage(null);
		deviceList.setSelectedIndex(0);
		trademarkList.setSelectedIndex(0);
		serialNumber.setText("");
	}
	
	public void init() {
		
		setLayout(null);
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				cameraPanel = getCameraPanel();
				cameraPanel.setBounds(350, 150, 640, 480);
				add(cameraPanel);
			}
		}).start();
		
		nameLabel =new JLabel("",JLabel.CENTER);
		nameLabel.setFont(new Font("Arial", Font.PLAIN, 35));
		nameLabel.setBounds(50, 50, 950, 50);
		nameLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
		add(nameLabel);
		
		documentLabel =new JLabel("",JLabel.CENTER);
		documentLabel.setFont(new Font("Arial", Font.PLAIN, 30));
		documentLabel.setBounds(50, 100, 950, 50);
		add(documentLabel);
		
		takePictureButton = new JButton();
		takePictureButton.setText("Tomar Foto");
		takePictureButton.setBounds(100,680,200,80);
		takePictureButton.setFont(new Font("Arial", Font.PLAIN, 30));
		add(takePictureButton);

		backButton = new JButton();
		backButton.setText("Volver");
		backButton.setBounds(100,560,200,80);
		backButton.setFont(new Font("Arial", Font.PLAIN, 30));
		add(backButton);
		
		dataLabel = new JLabel();
		dataLabel.setText("Registre su equipo:");
		dataLabel.setFont(new Font("Arial", Font.PLAIN, 30));
		dataLabel.setBounds(50, 140, 300, 50);
		add(dataLabel);
		
		serialLabel = new JLabel();
		serialLabel.setText("Serial:");
		serialLabel.setFont(new Font("Arial", Font.PLAIN, 30));
		serialLabel.setBounds(50, 190, 300, 50);
		add(serialLabel);
		
		serialNumber = new JTextField(40);
		serialNumber.setFont(new Font("Arial", Font.PLAIN, 30));
		serialNumber.setBounds(50, 240, 270, 50);
		add(serialNumber);
		
		keyboardButton = new JButton();
		keyboardButton.setText("Teclado");
		keyboardButton.setBounds(120, 300, 120, 40);
		keyboardButton.setFont(new Font("Arial", Font.PLAIN, 20));
		add(keyboardButton);
		keyboardButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					Runtime.getRuntime().exec("cmd /c C:\\Windows\\System32\\osk.exe");
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		
		deviceList = new JComboBox<String>(deviceString);
		deviceList.setBounds(50,360,250,60);
		deviceList.setFont(new Font("Arial", Font.PLAIN, 30));
		add(deviceList);
		deviceList.addActionListener (new ActionListener () {
		    public void actionPerformed(ActionEvent e) {
		    	@SuppressWarnings("unchecked")
				JComboBox <String> cb = (JComboBox <String>)e.getSource();
		        String device = (String)cb.getSelectedItem();
		        changeComboBox(device);
		    }
		});
		
		trademarkList = new JComboBox<String>(laptopString);
		trademarkList.setName(getName());
		trademarkList.setBounds(50,450,250,60);
		trademarkList.setFont(new Font("Arial", Font.PLAIN, 30));
		add(trademarkList);
		
		trademarkList.addPopupMenuListener(new PopupMenuListener() {
			
			@Override
			public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
				 JComboBox comboBox = (JComboBox) e.getSource();
			      Object popup = comboBox.getUI().getAccessibleChild(comboBox, 0);
			      Component c = ((Container) popup).getComponent(0);
			      if (c instanceof JScrollPane)
			      {
			         JScrollPane scrollpane = (JScrollPane) c;
			         JScrollBar scrollBar = scrollpane.getVerticalScrollBar();
			         Dimension scrollBarDim = new Dimension(40, scrollBar
			               .getPreferredSize().height);
			         scrollBar.setPreferredSize(scrollBarDim);
			      }
			}
			
			@Override
			public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {
				
			}
			
			@Override
			public void popupMenuCanceled(PopupMenuEvent arg0) {
				
			}
		});
		
		imageLabel = new JLabel();
		add(imageLabel);
		imageLabel.setVisible(false);
		
		takePictureButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				((WebcamPanel)cameraPanel).stop();
				BufferedImage image = new Camera().takePicture(webcam);
				startCamera();
				ImageSaved.getInstance().setImage(image);
				cameraPanel.setVisible(false);
				imageLabel.setBounds(350, 150, 640, 480);
				imageLabel.setIcon(new ImageIcon(image));
				
				imageLabel.setVisible(true);
			}
		});
		
		resetButton = new JButton();
		resetButton.setText("Repetir");
		resetButton.setBounds(410, 680, 200, 80);
		resetButton.setFont(new Font("Arial", Font.PLAIN, 30));
		add(resetButton);
		resetButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				cameraPanel.setVisible(true);
				imageLabel.setVisible(false);
			}
		});
		
		acceptButton = new JButton();
		acceptButton.setText("Aceptar");
		acceptButton.setBounds(720, 680, 200, 80);
		acceptButton.setFont(new Font("Arial", Font.PLAIN, 30));
		add(acceptButton);
		
		setFocusTraversalKeysEnabled(false);
		
		acceptButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					
					BufferedImage image = ImageSaved.getInstance().getImage();
					if (deviceList.getSelectedItem() .equals (deviceString[0]) || trademarkList.getSelectedItem() .equals(laptopString[0])){

						JOptionPane.showMessageDialog(null, "Debe seleccionar el dispositivo primero");
					}else{
						if (image == null) {

							JOptionPane.showMessageDialog(null, "Debe tomar la foto primero");
						} else {
							ByteArrayOutputStream os = new ByteArrayOutputStream();
							ImageIO.write(image, "gif", os);
							System.out.println(os.size());
							InputStream is = new ByteArrayInputStream(os.toByteArray());
							
							SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
							SimpleDateFormat sdfecha = new SimpleDateFormat("EEE, MMM d, ''yyyy");
							
							String device = (String)deviceList.getSelectedItem();
							String trademark = (String)trademarkList.getSelectedItem();
							String serial = serialNumber.getText();
							String ticketEnable = "enable";
							
							String codigo = String.valueOf(sdf.format(new Date())) + Constants.machineCode;
							boolean isSuccessful = SqlConnection.insertarCodigo(id, getPersonName(id), codigo, device, trademark, is, ticketEnable, serial);
							if (!isSuccessful) {
								JOptionPane.showMessageDialog(null, "Hay problemas de red, intente nuevamente");
								return;
							}
							String fecha = String.valueOf(sdfecha.format(new Date()));
							
							Code code = new Code();
							code.cedulaUsuario = id;
							code.nombreUsuario = getPersonName(id);
							code.fechaIngreso = fecha;
							code.codigo = codigo;
							if (emulatePrinter) {
								System.out.println(code.cedulaUsuario+"\r\n"+code.codigo);
							} else {
								Printer.print(code);
							}
					    	Keyboard frame = Keyboard.getInstance();
					    	frame.resetNumbers();
					    	frame.setVisible(true);
					    	TakePictureFrame.this.setVisible(false);
					    	ImageSaved.getInstance().setImage(null);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		});
		
		backButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
//					((WebcamPanel)cameraPanel).stop();
				} catch (Exception e) {
					e.printStackTrace();
				}
				TakePictureFrame.this.setVisible(false);
				Keyboard frame = Keyboard.getInstance();
				frame.setVisible(true);
				frame.resetNumbers();
				ImageSaved.getInstance().setImage(null);
			}
		});
	}
	
	public WebcamPanel getCameraPanel() {
		Webcam webcam = Webcam.getDefault();
		this.webcam = webcam;
		webcam.setViewSize(WebcamResolution.VGA.getSize());

		WebcamPanel panel = new WebcamPanel(webcam);
		panel.setMirrored(true);

		
		return panel; 
	}

	public void changeComboBox(String selection) {
		trademarkList.removeAllItems();
		if (selection.equals(deviceString[1])) {
			for (String item : laptopString) {
				trademarkList.addItem(item);
			}
		} else if (selection.equals(deviceString[2])) {
			for (String item : tabletString) {
				trademarkList.addItem(item);
			}
		} else if (selection.equals(deviceString[3])) {
			for (String item : camString) {
				trademarkList.addItem(item);
			}
		} else {
			for (String item : laptopString) {
				trademarkList.addItem(item);
			}
		}
	}
	
	public static String getPersonName(String id) {
		
		return SqlConnection.consultarNombre(id);

	}
	
	public void startCamera() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				((WebcamPanel)cameraPanel).start();
			}
		}).start();
	}
	
}
